﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace AcademicPlanner.Framework.Helpers
{
	/// <summary>
	/// SecurityHelper provides static helper methods for cryptography.
	/// </summary>
	/// <version>1.0</version>
	/// <since>1.0</since>
	public static class SecurityHelper
	{
		/// <summary>
		/// Hashes the given text using MD5.
		/// </summary>
		/// <param name="pText">The text to hash.</param>
		/// <param name="pSalt">The salt to use in the hash.</param>
		/// <returns>The hashed text and the salt.</returns>
		/// <version>1.0</version>
		/// <since>1.0</since>
		public static string Hash(string pText, string pSalt)
		{
			string rHash = "";
			var vHasher = new MD5CryptoServiceProvider();
			var vTextBytes = Encoding.UTF8.GetBytes(pText);
			var vSaltBytes = Encoding.UTF8.GetBytes(pSalt);
			var vBytesToHash = new byte[vTextBytes.Length+vSaltBytes.Length];

			for (int i = 0; i < vTextBytes.Length; i++)
				vBytesToHash[i] = vTextBytes[i];

			for (int i = 0; i < vSaltBytes.Length; i++)
				vBytesToHash[i] = vSaltBytes[i];

			var vHashed = vHasher.ComputeHash(vBytesToHash);
			var vHash = new byte[vHashed.Length + vSaltBytes.Length];

			for (int i = 0; i < vHashed.Length; i++)
				vHash[i] = vHashed[i];

			for (int i = 0; i < vSaltBytes.Length; i++)
				vHash[i] = vSaltBytes[i];

			rHash = Convert.ToBase64String(vHash);

			return rHash;
		}

		/// <summary>
		/// Returns a random unique hash obtained from <c>Guid.NewGuid</c>.
		/// </summary>
		/// <returns>A random unique hash.</returns>
		/// <version>1.0</version>
		/// <since>1.0</since>
		public static string RandomHash()
		{
			return Convert.ToBase64String(Guid.NewGuid().ToByteArray());
		}
	}
}
